package com.sdy.mvc.aop;

import com.sdy.mvc.annotation.TaskSync;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.stereotype.Component;

import java.util.concurrent.locks.Lock;

/**
 * @author zhouziqiang 
 */
@Slf4j
@Component
@Aspect
public class TaskRunOnceAop {
    @Autowired
    private RedisLockRegistry redisLockRegistry;
    @Value("${res.app.load-balance-index:0}")
    private Integer loadBalanceIndex;

    /**
     * task任务锁
     * @param pjp
     */
    @Around("execution(* com.sdy..*.*(..)) && @annotation(taskSync)")
    public Object around(ProceedingJoinPoint pjp, TaskSync taskSync) throws Throwable {
        if (loadBalanceIndex.equals(0)) {
            Signature signature = pjp.getSignature();
            Lock lock = redisLockRegistry.obtain("TaskRunOnceAop#".concat(signature.getDeclaringTypeName()).concat("#").concat(signature.getName()));
            if (lock.tryLock()) {
                try {
                    return pjp.proceed();
                } finally {
                    lock.unlock();
                }
            }
        }
        return null;
    }
}
